<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div v-show="showSearch">
				<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList" class="search-form-row">
					<el-row :gutter="10">
						<el-col :span="4">
							<el-form-item label="产品分类:" prop="category">
								<el-select v-model="state.queryForm.category" placeholder="请选择产品分类" clearable @change="categoryChange">
									<el-option v-for="(item,index) in categoryData" :key="index" :label="item.name" :value="item.identify"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="4">
							<el-form-item label="产品:" prop="productKey">
								<el-select v-model="state.queryForm.productKey" placeholder="请选择产品" clearable>
									<el-option v-for="item in productData" :key="item.id" :label="item.name" :value="item.productKey" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="4">
						<el-form-item label="状态:" prop="onlineStatus">
							<el-select v-model="state.queryForm.onlineStatus" placeholder="请选择状态" >
								<el-option label="在线" value="1" />
								<el-option label="离线" value="0" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="设备id:" prop="unitNo">
							<el-input v-model="state.queryForm.unitNo" placeholder="请输入设备id"  />
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="设备名称:" prop="deviceName">
							<el-input v-model="state.queryForm.deviceName" placeholder="请输入设备名称"  />
						</el-form-item>
						</el-col>
						<el-col :span="4">
							<el-form-item>
								<el-button formDialogRef icon="search" type="primary" @click="getDataList">查询</el-button>
								<el-button formDialogRef icon="Refresh" @click="resetQuery">重置</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-row>
				<div class="mb10" style="width: 100%">
					<el-button
						class="ml10"
						icon="folder-add"
						v-auth="'access_accessDeviceInfo_add'"
						type="primary"
						@click="formDialogRef.openDialog(null, 'add')"
					>
						新增
					</el-button>
					<el-button class="ml10"  icon="upload-filled" plain type="primary"  @click="openBatchAddDialog"> 导入 </el-button>
					<el-button class="ml10" icon="Delete" v-auth="'access_accessDeviceInfo_del'" :disabled="multiple" type="primary" @click="handleDelete1(selectObjs)"> 删除 </el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						v-auth="'access_accessDeviceInfo_view'"
						:export="'access_accessDeviceInfo_export'"
						class="ml10"
						style="float: right; margin-right: 20px"
						@queryTable="getDataList"
						@exportExcel="exportExcel"
					>
						<el-tooltip effect="dark" content="卡片模式" placement="top">
							<el-button v-show="cardType === 'card'" circle icon="Grid" @click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')" />
						</el-tooltip>
						<el-tooltip effect="dark" content="列表模式" placement="top">
							<el-button v-show="cardType === 'table'" circle icon="List" @click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')" />
						</el-tooltip>
					</right-toolbar>
				</div>
			</el-row>
			<!-- 列表 -->
      <DevCode ref="devCodeRef"></DevCode>
			<el-table
				v-loading="state.loading"
				:data="state.dataList"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				class="tableClass"
				@selection-change="handleSelectionChange"
				v-show="cardType === 'table'"
			>
			<el-table-column type="selection" width="40" />
				<el-table-column type="index" label="序号" width="100" />
				<!-- <el-table-column prop="unitNo" label="设备ID" width="300" /> -->
				<el-table-column prop="deviceName" label="设备名称" />
				<el-table-column prop="productName" label="所属产品" />
				<el-table-column prop="subareaCn" label="所属位置" />
				<el-table-column prop="unitNo" label="二维码" >
          <template #default="scope">
            <div class='qr' v-if='scope.row.unitNo' @click="openDialog(scope.row)">
              <vueQr class='qr-code' :text='scope.row.unitNo' :size='30' />
            </div>
          </template>
        </el-table-column>
				<el-table-column prop="onlineStatus" label="状态">
					<template #default="scope">
						<span v-if="scope.row.onlineStatus === 1" type="success">在线</span>
						<span v-else type="danger">离线</span>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" />
				<!-- <el-table-column prop="createTime" label="创建时间" /> -->
				<el-table-column fixed="right" label="操作" width="350" align="center">
					<template #default="scope">
						<el-button icon="view" text type="primary" @click="detailDialogRef.openDialog(scope.row)">详情 </el-button>
						<el-button icon="edit-pen" text type="primary" @click="formDialogRef.openDialog(scope.row, 'edit')">修改 </el-button>
						<el-button icon="lock" text type="primary" v-if="scope.row.useStatus == 1" @click="changeStatus(scope.row.id, '0')">停用 <el-tooltip
									class="box-item"
									effect="dark"
									placement="top"
								>
									<template #content>
										<div>启用： 启动接收该设备上报数据</div>
										<div>停用： 停止接收该设备上报数据</div>
									</template>
									<el-icon style="margin-left: 5px"><QuestionFilled /></el-icon>
								</el-tooltip></el-button>
						<el-button icon="unlock" text type="primary" v-else @click="changeStatus(scope.row.id, '1')">启用 <el-tooltip
									class="box-item"
									effect="dark"
									placement="top"
								>
									<template #content>
										<div>启用： 启动接收该设备上报数据</div>
										<div>停用： 停止接收该设备上报数据</div>
									</template>
									<el-icon style="margin-left: 5px"><QuestionFilled /></el-icon>
								</el-tooltip></el-button>
						<el-button icon="DocumentCopy" text type="primary" @click="copyId(scope.row.unitNo)">复制ID</el-button>
						<el-button icon="delete" text type="primary" @click="handleDelete(scope.row.id)">删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 卡片 -->
			<div v-show="cardType === 'card'" class="cardClass">
				<el-card v-loading="state.loading" class="card" shadow="hover" v-for="item in state.dataList" :key="item.id">
					<el-row class="cardRow">
						<span class="cardTitle">{{ item.deviceName }}</span>
					</el-row>
					<el-row>
						<el-col :span="18" class="card-main">
							<!-- <el-row class="cardRow">
								<el-tooltip class="box-item" effect="dark" placement="top">
									<template #content>{{ item.unitNo }}</template>
									<span>设备ID：{{ item.unitNo?.substring(0, 25) + '...' }}</span>
								</el-tooltip>
							</el-row> -->
							<el-row class="cardRow">
								<span>所属产品：</span>
								<el-tooltip class="box-item" effect="dark" placement="top" :content="item.productName"><span  class="text-product">{{ item.productName}}</span></el-tooltip>
							</el-row>
							<el-row class="cardRow">
								<span>所属位置：{{ item.subareaCn }}</span>
							</el-row>
							<el-row class="cardRow">
								<span>状态：{{ item.onlineStatus == 0 ? '离线' : '在线' }}</span>
							</el-row>
						</el-col>
						<el-col :span="6">
							<el-row>
								<div style="width: 100px; height: 100px">
									<img v-if="item.productImg" :src="baseURL + item.productImg" width="100px" height="100px" alt="" />
									<img v-else src="/@/assets/pic_device.png" width="100px" height="100px" alt="" />
								</div>
							</el-row>
						</el-col>
					</el-row>

					<template #footer>
						<div class="cardFooter">
							<el-button link type="primary" @click="detailDialogRef.openDialog(item)">详情 </el-button>
							<el-button link type="primary" @click="formDialogRef.openDialog(item, 'edit')">修改 </el-button>
							<el-button link type="primary" v-if="item.useStatus == 1" @click="changeStatus(item.id, '0')">停用 
								<el-tooltip
									class="box-item"
									effect="dark"
									placement="top"
								>
									<template #content>
										<div>启用： 启动接收该设备上报数据</div>
										<div>停用： 停止接收该设备上报数据</div>
									</template>
									<el-icon style="margin-left: 5px"><QuestionFilled /></el-icon>
								</el-tooltip>
								
							</el-button>
							<el-button link type="primary" v-else @click="changeStatus(item.id, '1')">启用 
								<el-tooltip
									class="box-item"
									effect="dark"
									placement="top"
								>
									<template #content>
										<div>启用： 启动接收该设备上报数据</div>
										<div>停用： 停止接收该设备上报数据</div>
									</template>
									<el-icon style="margin-left: 5px"><QuestionFilled /></el-icon>
								</el-tooltip>
							</el-button>
							<el-button link type="primary" @click="copyId(item.unitNo)">复制ID</el-button>
							<el-button link type="primary" @click="handleDelete(item.id)">删除 </el-button>
						</div>
					</template>
				</el-card>
			</div>
			<pagination v-bind="state.pagination" @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
			<!-- 编辑、新增  -->
			<form-dialog ref="formDialogRef" @refresh="getDataList(false)" :productData="productData" />
			<!-- 批量新增设备 -->
			<el-dialog v-model="visible" :close-on-click-modal="false" title="批量添加设备" draggable width="30%">
				<el-form ref="dataFormRef" :rules="importFormRules" v-loading="importLoading" :model="importForm" label-width="90px">
					<el-row :gutter="24">
						<el-col :span="24" class="mb20">
							<el-form-item label="所属产品:" prop="productKey">
								<el-select v-model="importForm.productKey" placeholder="请选择产品">
									<el-option v-for="item in productData" :key="item.id" :label="item.name" :value="item.productKey" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="24">
						<el-col :span="24" class="mb20">
							<el-form-item label="上传文件:" prop="fileList">
								<el-upload
									v-model:file-list="importForm.fileList"
									style="width: 100%"
									ref="uploadRef"
									:limit="1"
									accept=".xlsx, .xls"
									:headers="headers"
									:data="importData"
									action="/admin/accessDeviceInfo/import"
									:auto-upload="false"
									drag
								>
									<i class="el-icon-upload"></i>
									<div class="el-upload__text">
										{{ $t('excel.operationNotice') }}
										<em>{{ $t('excel.clickUpload') }}</em>
									</div>
									<template #tip>
										<div class="el-upload__tip">
											仅允许导入xls、xlsx格式文件。
											<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downExcelTemp"
												>{{ $t('excel.downloadTemplate') }}
											</el-link>
										</div>
									</template>
								</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
						<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
					</span>
				</template>
			</el-dialog>
			<!-- 详情弹窗 -->
			<detail-dialog ref="detailDialogRef" />
		</div>
	</div>
</template>

<script lang="ts" name="device" setup>
import { fetchList, delObjs, editObj, importDev } from '/@/api/basiciot/device/device';
import { fetchList as productList } from '/@/api/basiciot/device/product';
import { fetchList as getCategoryList } from '/@/api/basiciot/device/category';
import { onMounted, reactive, ref } from 'vue';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useI18n } from 'vue-i18n';
import { fileList } from '/@/api/admin/file';
import { Session } from '/@/utils/storage';
import other from '/@/utils/other';
import useClipboard from 'vue-clipboard3';
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import DevCode from "/@/views/basiciot/device/devmanagement/devCode.vue";
const { t } = useI18n();
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const DetailDialog = defineAsyncComponent(() => import('./detail.vue'));
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	createdIsNeed: false,
	pagination: {
		current: 1,
		size: 12,
		total: 0,
	},
});
const dataFormRef = ref();
const importLoading = ref(false);
//获取产品品类关联数据
const categoryData:any = ref([]);

// 提交表单数据
const importForm = reactive({
	productKey: '',
	fileList: [],
});
// 请求头处理
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + Session.get('token'),
	};
});
const multiple = ref(true);
// 多选rows
const selectObjs = ref([]) as any;

const uploadRef = ref();
const visible = ref(false);
const formDialogRef = ref();
const detailDialogRef = ref();
const productData = ref([]);
const cardType = ref('card');
const showSearch = ref(true);
const queryRef = ref();
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);
// 清空搜索条件
const resetQuery = () => {
	queryRef.value.resetFields();
	getDataList();
};
// 定义校验规则
const importFormRules = ref({
	productKey: [{ required: true, message: '所属产品不能为空', trigger: 'blur' }],
	fileList: [{ required: true, message: '文件不能为空', trigger: 'blur' }],
});
const handleChange = (file: any) => {
	importForm.fileList = file;
};
const importData = computed(() => {
	return { productKey: importForm.productKey };
});

const categoryChange = (val) => {
	state.queryForm.productKey = ''
	productList({ category: val, size: 9999 }).then((res) => {
		productData.value = res.data.records;
	});
}

// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

//打开批量添加设备
const openBatchAddDialog = () => {
	visible.value = true;
	dataFormRef.value.resetFields();
};
//批量添加设备
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	importLoading.value = true;
	importDev({
		productKey: importForm.productKey,
		file: importForm.fileList[0].raw,
	})
		.then((res) => {
			if (res.ok) {
				useMessage().success('导入成功');
				visible.value = false;
				importLoading.value = false;
				getDataList();
			}
		})
		.catch((err) => {
			useMessage().error(err.msg);
			importLoading.value = false;
		});
};
//下载模板
const downExcelTemp = () => {
	other.downBlobFile(other.adaptationUrl('/admin/sys-file/local/file/device.xlsx'), {}, '批量添加设备模板.xlsx');
};

// 导出excel
const exportExcel = () => {
	other.downBlobFile(other.adaptationUrl('/bm/accessDevice/export'), Object.assign(state.queryForm, { ids: selectObjs }), '设备列表.xlsx')
};

// 删除操作
const handleDelete = (id: string) => {
	useMessageBox()
		.confirm(t('common.delConfirmText'))
		.then(() => {
			delObjs([id])
				.then(() => {
					getDataList();
					useMessage().success(t('common.delSuccessText'));
				})
				.catch((err: any) => {
					useMessage().error(err.msg);
				});
		});
};
const handleDelete1 = (ids: Array<string>) => {
	useMessageBox()
		.confirm(t('common.delConfirmText'))
		.then(() => {
			delObjs(ids)
				.then(() => {
					getDataList();
					useMessage().success(t('common.delSuccessText'));
				})
				.catch((err: any) => {
					useMessage().error(err.msg);
				});
		});
};
//停用启用
const changeStatus = (id: string, status: string) => {
	editObj({
		id: id,
		useStatus: status,
	}).then((res) => {
		getDataList();
		useMessage().success('操作成功');
	});
};

const { toClipboard } = useClipboard();
// 复制id
const copyId = async (id: string) => {
	try {
		await toClipboard(id);
		useMessage().success('复制成功');
	} catch (e) {
		useMessage().error('复制失败');
	}
};
const devCodeRef=ref(null)
const openDialog=(row)=>{
  devCodeRef.value.dialogVisible = true
  devCodeRef.value.codeData = row
}
onMounted(() => {
	getDataList();
	getCategoryList({ current: 1, size: 9999 }).then((res) => {
		categoryData.value = res.data.records;
	});
	productList({size: 9999 }).then((res) => {
		productData.value = res.data.records;
	});
	
});
</script>
<style scoped lang="scss">
.tableClass {
	min-height: vh(580);
}
.cardClass {
	min-height: vh(580);
	display: flex;
	flex-wrap: wrap;
	overflow-y: scroll;
	.card {
		width: 24%;
		height: 230px;
		margin: 0 15px 15px 0;
	}
	.cardRow {
		margin-bottom: 10px;
	}
	.cardTitle {
		font-size: 16px;
		font-weight: 600;
	}
	.cardFooter {
		display: flex;
		justify-content: space-between;
	}
}
.card-main {
	.cardRow:last-child {
		margin-bottom: 0;
	}
}
.text-product {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	flex: 1;
}
</style>
